package xin.nick.exception;

import io.swagger.v3.oas.annotations.Hidden;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xin.nick.entity.Result;
import xin.nick.entity.ResultCode;
import xin.nick.util.ResultUtil;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Nick
 * @since 2023/4/15
 */
@Hidden
@RestController
@RequestMapping("${server.error.path:${error.path:/error}}")
public class ExceptionController implements ErrorController {

    @RequestMapping
    public void error(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpStatus status = getStatus(request);
        response.setStatus(status.value());
        if (status == HttpStatus.NOT_FOUND) {
            ResultUtil.responseResult(response, Result.custom(ResultCode.NOT_FOUND));
        } else {
            ResultUtil.responseResult(response, Result.custom(ResultCode.SERVER_ERROR));
        }

    }

    protected HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        try {
            return HttpStatus.valueOf(statusCode);
        }
        catch (Exception ex) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }
}
